<template>
  <div class="app-container">
    <div style="padding-bottom: 20px">
      <!-- <div>目前只有oppo和vivo的收益可以获取</div><br> -->
      <el-button type="primary" @click="dialogVisible=true">生成收益报表</el-button>
      
    </div>
    <div class="filter-container">
      <el-select
        v-if="userType == 'all'"
        v-model="listQuery.proxy"
        placeholder="请选择代理"
        clearable
        filterable
        style="width: 150px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="(item, index) in dailiArr"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-date-picker
        v-model="value1"
        align="left"
        unlink-panels
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item pickertime"
        format="yyyy-MM-dd"
        value-format="timestamp"
        :picker-options="pickerOptions2"
        @change="handleFilter"
      />
      <template>
        <el-select
          v-model="listQuery.status"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 150px"
          class="filter-item"
          @change="handleFilter"
        >
          <el-option label="全部" value="" />
          <el-option label="已结算" value="1" />
          <el-option label="未结算" value="2" />
          <el-option label="已作废" value="3" />
        </el-select>
      </template>
      <a-button type="primary" size="large" @click="handleFilter">
        搜索
      </a-button>
      <!-- <el-button v-waves class="filter-item" plain size="small" type="primary" icon="el-icon-refresh" @click="handleCancel">
        重置
      </el-button> -->
      <span style="margin-left: 20px" />
    </div>

    <el-table
      :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        show-summary
        style="width: 100%"
    >
      <!-- <el-table-column label="日期" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.time_ }}</span>
        </template>
      </el-table-column> -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="oppo_uv:">
              <span>{{ props.row.detail_.oppo.uv }}</span>
            </el-form-item>
            <el-form-item label="vivo_uv:">
              <span>{{ props.row.detail_.vivo.uv }}</span>
            </el-form-item>
            <el-form-item label="xiaomi_uv:">
              <span>{{ props.row.detail_.xiaomi.uv }}</span>
            </el-form-item>
            <el-form-item label="huawei_uv:">
              <span>{{ props.row.detail_.huawei.uv }}</span>
            </el-form-item>

            <el-form-item label="oppo_pv:">
              <span>{{ props.row.detail_.oppo.pv }}</span>
            </el-form-item>
            <el-form-item label="vivo_pv:">
              <span>{{ props.row.detail_.vivo.pv }}</span>
            </el-form-item>
            <el-form-item label="xiaomi_pv:">
              <span>{{ props.row.detail_.xiaomi.pv }}</span>
            </el-form-item>
            <el-form-item label="huawei_pv:">
              <span>{{ props.row.detail_.huawei.pv }}</span>
            </el-form-item>

            <el-form-item label="oppo_ex:">
              <span>{{ props.row.detail_.oppo.ex }}</span>
            </el-form-item>
            <el-form-item label="vivo_ex:">
              <span>{{ props.row.detail_.vivo.ex }}</span>
            </el-form-item>
            <el-form-item label="xiaomi_ex:">
              <span>{{ props.row.detail_.xiaomi.ex }}</span>
            </el-form-item>
            <el-form-item label="huawei_ex:">
              <span>{{ props.row.detail_.huawei.ex }}</span>
            </el-form-item>

            <el-form-item label="oppo收益:">
              <span>{{ props.row.detail_.oppo.money }}</span>
            </el-form-item>
            <el-form-item label="vivo收益:">
              <span>{{ props.row.detail_.vivo.money }}</span>
            </el-form-item>
            <el-form-item label="xiaomi收益:">
              <span>{{ props.row.detail_.xiaomi.money }}</span>
            </el-form-item>
            <el-form-item label="huawei收益:">
              <span>{{ props.row.detail_.huawei.money }}</span>
            </el-form-item>

            <el-form-item label="oppo单价:">
              <span>{{ props.row.detail_.oppo.price }}</span>
            </el-form-item>
            <el-form-item label="vivo单价:">
              <span>{{ props.row.detail_.vivo.price }}</span>
            </el-form-item>
            <el-form-item label="xiaomi单价:">
              <span>{{ props.row.detail_.xiaomi.price }}</span>
            </el-form-item>
            <el-form-item label="huawei单价:">
              <span>{{ props.row.detail_.huawei.price }}</span>
            </el-form-item>

            <el-form-item label="oppo真实收益:">
              <span>{{ props.row.detail_.oppo.true_money }}</span>
            </el-form-item>
            <el-form-item label="vivo真实收益:">
              <span>{{ props.row.detail_.vivo.true_money }}</span>
            </el-form-item>
            <el-form-item label="xiaomi真实收益:">
              <span>{{ props.row.detail_.xiaomi.true_money }}</span>
            </el-form-item>
            <el-form-item label="huawei真实收益:">
              <span>{{ props.row.detail_.huawei.true_money }}</span>
            </el-form-item>
            
          </el-form>
        </template>
      </el-table-column>
      <el-table-column  key="1" label="日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.period }}</span>
        </template>
      </el-table-column>
      <el-table-column  key="2" label="用户名" min-width="80" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column key="4" label="UV" prop="uv" min-width="100" align="center"></el-table-column>
      <el-table-column key="5" label="PV" prop="pv" min-width="100" align="center"></el-table-column>
      <el-table-column key="6" label="点击数量" prop="ex" min-width="100" align="center"></el-table-column>
      <el-table-column  key="10" label="点击单价" min-width="100" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column  key="7" label="总收益" prop="money" min-width="100" align="center"></el-table-column>
      <el-table-column  key="11" label="抽成比例%" min-width="100" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.take_percentag }}</span>
        </template>
      </el-table-column>
      <el-table-column  key="9" label="真实收益" prop="true_money" min-width="100" align="center"></el-table-column>
      <el-table-column key="12" label="状态" min-width="80" align="center">
        <template slot-scope="{ row }">
          <!-- <el-link :type="row.status | statusFilter"> -->
          {{ allStatus[row.status] }}
          <!-- </el-link> -->
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        min-width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <a-button
            type="link"
            :disabled="row.status != 2"
            size="small"
            @click="handleSettle(row, '结算')"
          >
            结算
          </a-button>
          <a-button
            type="link"
            size="small"
            :disabled="row.status != 2"
            @click="handleSettle(row, '删除')"
          >
            删除
          </a-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      class="pageShow"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />
    <div>
      <el-dialog
        title="生成收益报表"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <div>

          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="报表的日期" prop="data_value">
              <el-date-picker
                v-model="ruleForm.data_value"
                align="right"
                type="date"
                placeholder="选择日期"
                value-format="timestamp"
                :picker-options="pickerOptions">
              </el-date-picker>
              <span></span>
            </el-form-item>
            <el-form-item label="oppo收益" prop="oppo">
              <el-input v-model="ruleForm.oppo"></el-input>
            </el-form-item>
            <el-form-item label="vivo收益" prop="vivo">
              <el-input v-model="ruleForm.vivo"></el-input>
            </el-form-item>
            <el-form-item label="xiaomi收益" prop="xiaomi">
              <el-input v-model="ruleForm.xiaomi"></el-input>
            </el-form-item>
            <el-form-item label="huawei收益" prop="huawei">
              <el-input v-model="ruleForm.huawei"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')" :loading="sub_loading">立即生成</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {
  getSettleList,
  getProxyNameList,
  changeSettleStatus,
  createSettleList
} from "@/api/admin/admin";

import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { MessageBox, Message } from "element-ui";

export default {
  name: "Settle",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "success",
        0: "danger",
        2: "info",
      };
      return statusMap[status];
    },
  },
  data() {
    var int_float = (rule, value, callback) => {
      console.log(value)
        if(value == '0' || value == 0){
          callback();
        }
        if (/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value) == false) {
          callback(new Error("请输入正整数或两位小数"));
        } else {
          callback();
        }
      }
    return {
      sub_loading: false,
      dialogVisible: false,
      userType: this.$store.state.user.type,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      value1: "",
      countPv: "",
      countUv: "",
      countProfit: "",
      allStatus: {
        1: "已结算",
        2: "未结算",
        3: "已作废",
      },
      dailiArr: [],
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      listQuery: {
        page: 1,
        page_size: 20,
        proxy: "",
        time_start: "",
        time_end: "",
        status: "",
      },
      ruleForm: {
        data_value: '',
        datetime_: '',
        oppo: '',
        vivo: '',
        xiaomi: '',
        huawei: ''
      },
      rules: {
        data_value: [
          { required: true, message: '请选择日期', trigger: 'change' },
        ],
        oppo: [
          { required: true, message: '请输入oppo收益', trigger: 'change' },
          { validator: int_float, trigger: 'change' }
        ],
        vivo: [
          { required: true, message: '请输入vivo收益', trigger: 'change' },
          { validator: int_float, trigger: 'change' }
        ],
        xiaomi: [
          { required: true, message: '请输入xiaomi收益', trigger: 'change' },
          { validator: int_float, trigger: 'change' }
        ],
        huawei: [
          { required: true, message: '请输入huawei收益', trigger: 'change' },
          { validator: int_float, trigger: 'change' }
        ]
      },
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
    };
  },
  created() {
    this.getProxyNameList();
    this.getList();
  },
  methods: {
    handleClose(){
      this.dialogVisible = false
      this.ruleForm = {
        data_value: '',
        datetime_: '',
        oppo: '',
        vivo: '',
        xiaomi: '',
        huawei: ''
      }
    },
    // 生成收益报表
    submitForm(formName) {
      this.ruleForm.datetime_ = this.ruleForm.data_value / 1000
      // console.log(this.ruleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.sub_loading = true
            createSettleList(this.ruleForm).then(res => {
              if(res.STATUS == 200){
                Message({
                  message: res.DEC,
                  type: "success",
                  duration: 2000,
                });
                this.handleClose()
                this.getList()
              }else{
                Message({
                  message: res.DEC,
                  type: "error",
                  duration: 2000,
                });
              }
            })
            this.sub_loading = false
            // alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    getList() {
      this.listLoading = true;
      if (this.value1) {
        this.listQuery.time_start = this.value1[0] / 1000;
        this.listQuery.time_end = this.value1[1] / 1000;
      } else {
        this.listQuery.time_start = "";
        this.listQuery.time_end = "";
      }
      getSettleList(this.listQuery).then((response) => {
        this.list = response.DATA.list;
        this.total = response.DATA.total;
        this.countPv = response.DATA.sum.pv;
        this.countUv = response.DATA.sum.uv;
        this.countProfit = response.DATA.sum.money;
        this.listLoading = false;
      });
    },

    //获取代理列表
    getProxyNameList() {
      getProxyNameList().then((r) => {
        this.dailiArr = r.DATA;
      });
    },
    getSummaries() {
      const sums = [
        "总计",
        "-",
        "-",
        this.countUv,
        this.countPv,
        "-",
        this.countProfit,
        "-",
        "-",
      ];
      return sums;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCancel() {
      this.value1 = "";
      this.listQuery.page = 1;
      this.listQuery.proxy = "";
      this.listQuery.status = "";
      this.getList();
    },
    handleSettle(row, title) {
      MessageBox.confirm(`确定${title}吗？`, "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            id: row.id,
            status: title == "结算" ? 1 : 3,
          };

          changeSettleStatus(obj).then((response) => {
            if (response.STATUS === 200) {
              this.getList();
              Message({
                message: response.DEC || `${title}成功`,
                type: "success",
                duration: 2000,
              });
            } else {
              Message({
                message: response.DEC || `${title}成功`,
                type: "error",
                duration: 2000,
              });
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 24%;
  }
.pageHidden {
  display: none;
}
@media (max-width: 550px) {
  .pageShow {
    display: none;
  }
  .pageHidden {
    display: block;
  }
  .pickertime {
    width: 100%;
  }
}
.filter-item {
  margin-bottom: 3px;
}
</style>
